package org.robot.scm.utils;

import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.config.NightMode;
import org.robot.scm.pojos.enums.PlatformEnum;

/**
 * @Author : Awn create on 2024/6/6 16:39
 */
@Slf4j
public class CallHelper {

    /**
     * callVo
     * title 用于过滤关键字，符合条件才打， 五分钟内 只能打一次限制
     */
    public synchronized static void callOutOf5(BaseConfig baseConfig, String title, boolean isMe) {
        NightMode nightMode = baseConfig.get().getNightMode();
        if (nightMode.isNight(baseConfig) && nightMode.isInclude(baseConfig, PlatformEnum.TELEGRAM)) {
            log.info("night mode is hung up, title: {}", title);
            return;
        }

        String wxid = baseConfig.getCurrentPlatform().getCallVoIp();
        String callKey = RedisCacheHelper.get("call-" + wxid);
        if (StringUtils.isNotBlank(callKey)) {
            // 我发信息后, 给锁续命5分钟, 防止频繁打电话
            if (isMe) {
                RedisCacheHelper.put("call-" + wxid, wxid, 300);
            }
            return;
        }
        RedisCacheHelper.put("call-" + wxid, wxid, 300);
        if (baseConfig.getCurrentPlatform().getKeywords().contains(title) && StringUtils.isNotBlank(wxid)) {
            CompletableFuture.runAsync(() -> RequestHelper.post(baseConfig.robotUrl(), baseConfig.robotCall(wxid)));
        }
    }

    public synchronized static boolean callById(BaseConfig baseConfig, String wxid) {
        if (StringUtils.isBlank(wxid)) {
            log.error("call id cannot null");
            return false;
        }
        String callKey = RedisCacheHelper.get("call-" + wxid);
        if (StringUtils.isNotBlank(callKey)) {
            return false;
        }
        RedisCacheHelper.put("call-" + wxid, wxid, 30);
        CompletableFuture.runAsync(() -> RequestHelper.post(baseConfig.robotUrl(), baseConfig.robotCall(wxid)));
        return true;
    }
}
